package gui;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class JImagePanel extends JPanel {

	private BufferedImage image;  
	int x, y;  
	public JImagePanel(BufferedImage image, int x, int y) {  
		super();  
		this.image = image;
		this.x = x;  
		this.y = y;  
	}  

	public JImagePanel()
	{
		super();
	}

	public void paintComponent(Graphics g) {  
		super.paintComponent(g);
		try {
			g.drawImage(resize(image, this.getWidth(), this.getHeight()), x, y, null);
		}
		catch (NullPointerException e) {
		}
	}  

	public void setImage(String imagepath) throws IOException {
		BufferedImage img = ImageIO.read(new File(imagepath));
		this.image = img;
		repaint();
	}

	private static BufferedImage resize(BufferedImage img, int newW, int newH) {  
		int w = img.getWidth();  
		int h = img.getHeight();  
		BufferedImage dimg = new BufferedImage(newW, newH, img.getType());  
		Graphics2D g = dimg.createGraphics();  
		g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);  
		g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);  
		g.dispose();  
		return dimg;  
	}

}
